package com.peanut.controller;

import com.mvc.annotation.RequestBody;
import com.mvc.annotation.RequestMapping;
import com.mvc.annotation.ResponseBody;
import com.mvc.annotation.Valid;
import com.peanut.constants.Constants;
import com.peanut.entity.AdminUser;
import com.peanut.entity.JsonResult;
import com.peanut.entity.Menu;
import com.peanut.service.MenuService;
import com.spring.annotation.Autowired;
import com.spring.annotation.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class MenuController {
	@Autowired
	private MenuService service;
	
	
	@ResponseBody
	@RequestMapping("/menu/query.do")
	public JsonResult queryMenu() {
		List<Menu> menus = service.listAll();
		return JsonResult.success(menus);
	}
	
	
	@RequestMapping("/menu/update.do")
	@ResponseBody
	public JsonResult addMenu(@RequestBody @Valid Menu menu) {
		boolean b = false;
		if (menu.getParentId() == null) {
			menu.setParentId(0);
		}
		if (menu.getId() == null) {
			b = service.save(menu);
		} else {
			b = service.update(menu);
		}
		if (b) {
			return JsonResult.success();
		}
		return JsonResult.fail();
	}
	
	@ResponseBody
	@RequestMapping("/menu/delete.do")
	public JsonResult deleteMenu(int id) {
		if (service.removeById(id)) {
			return JsonResult.success();
		}
		return JsonResult.fail();
	}
	
	
	
	
	@ResponseBody
	@RequestMapping("/menu/queryMyMenu.do")
	public JsonResult queryMyMenu(HttpServletRequest request) {
		HttpSession session = request.getSession();
		AdminUser loginUser = (AdminUser) session.getAttribute(Constants.LOGIN_USER);
		
		
		Integer roleId = loginUser.getRoleId();
		
		return JsonResult.success(service.queryMyMenuTree(roleId));
	}
	
	
	/**
	 * 查询全部 树形菜单数据
	 */
	@ResponseBody
	@RequestMapping("/menu/queryTree.do")
	public JsonResult queryMenuTree() {
		return JsonResult.success(service.queryMenuTree());
	}
}
